package com.yy.service;

import com.yy.mapper.PowerMapper;
import com.yy.mapper.RoleMapper;
import com.yy.mapper.UserMapper;
import com.yy.pojo.*;
import com.yy.pojo.User;
import com.yy.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
//import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author YY
 */

@Component
@Service
@Transactional
public class UserService {
    @Resource
    @Autowired
    private UserMapper userMapper;
    @Resource
    private PowerMapper powerMapper;
    @Resource
    private RoleMapper roleMapper;

    public User getUserByid(String uid) {
        return userMapper.getUserByid(uid);
    }

    public User findUserByName(String uname) {
        return userMapper.findUserByName(uname);
    }



    public void addUser(User user,UserRole userRole){
        String username = user.getUname();
        User result = userMapper.findByUserName(username);
        if (result != null){
            throw new UserNameDoplicatedException("尝试添加的用户名[" + username + "]已经被占用");
        }
        //加密
        String salt = UUID.randomUUID().toString().toUpperCase();
        String md5Password = getMd5Password(user.getPwd(), salt);
        user.setPwd(md5Password);
        user.setSalt(salt);
        userRole.setUserId(user.getUid());
        userMapper.insertRole(userRole);
        Integer rows = userMapper.insert(user);
        if (rows != 1)
        {
            throw new InsertException("添加用户过程中发生未知异常");
        }
    }

    public void addRole(UserRole userRole){
        Integer rows = userMapper.insertRole(userRole);
        if (rows != 1)
        {
            throw new InsertException("添加角色过程中发生未知异常");
        }
    }

    /**
     * 执行密码加密
     * @param password 原始密码
     * @param salt 盐值
     * @return 加密后的密文
     */
    private String getMd5Password(String password, String salt) {
        /*
         * 加密规则：
         * 1、无视原始密码的强度
         * 2、使用UUID作为盐值，在原始密码的左右两侧拼接
         * 3、循环加密3次
         */
        for (int i = 0; i < 3; i++) {
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        return password;
    }


    public User login(String username, String password) {
        User result = userMapper.findByUserName(username);
        if (result == null) {
            throw new UserNotFoundException("用户数据不存在");
        }
        //解密
        String salt = result.getSalt();
        String md5Password = getMd5Password(password, salt);
        if (!result.getPwd().equals(md5Password)) {
            throw new PasswordNotMatchException("用户名或密码错误");
        }
        List<Role> userRoles = roleMapper.roleFindByUname(username);
        List<Power> rolePowers = powerMapper.powerFoundByUname(username);
        User user = new User();
        user.setUid(result.getUid());
        user.setUname(result.getUname());
        user.setPowers(rolePowers);
        user.setRoles(userRoles);
        return user;
    }


    public User getByUid(String userId) {
        User result = userMapper.findByUid(userId);
        if (result == null) {
            throw new UserNotFoundException("用户数据不存在");
        }
        User user = new User();
        user.setUname(result.getUname());
        return user;
    }


    public User getByUname(String uname) {
        User result = userMapper.findByUserName(uname);
        if (result == null) {
            throw new UserNotFoundException("用户数据不存在");
        }

        User user = new User();
        user.setUname(result.getUname());

        return user;
    }


    public void deleteUser(String uname) {
        User result = userMapper.findByUserName(uname);
        if (result == null){
            throw new UserNotFoundException("用户数据不存在");
        }
//        if (!result.getUserId().equals(uname)){
//            throw new UserDeniedException("非法数据访问");
//        }
        Integer rows = userMapper.deleteByUname(uname);
        if (rows != 1){
            throw new DeleteException("删除数据时产生未知异常");
        }
    }


    public List<User> getUserList() {
        List<User> list = userMapper.findUserList();
        for (User user : list){
            user.setPwd(null);
            user.setSalt(null);
        }
        return list;
    }

    public List<User> getRole(){
        List<User> list = userMapper.findRole();
        return list;
    }

    public void changeInfo(String uid, User user){
        User result = userMapper.findByUid(uid);
        if (result == null){
            throw new UserNotFoundException("用户数据不存在");
        }
        String salt = UUID.randomUUID().toString().toUpperCase();
        String md5Password = getMd5Password(user.getPwd(), salt);
        user.setPwd(md5Password);
        user.setSalt(salt);
        Integer rows = userMapper.updateUser(user);
        if (rows != 1){
            throw new UpdateInfoException("修改用户信息时产生异常错误");
        }
    }
}
